package com.waidi.clothespad.thread;
import android.os.Bundle;
import android.os.Handler;
import android.content.Context;
import java.io.File;
import java.lang.Thread;

import android.os.Message;
import android.util.Log;

import com.waidi.clothespad.common.Config;
import com.waidi.clothespad.common.Db;
import com.waidi.clothespad.common.DevData;
import com.waidi.clothespad.common.MyBroadcastReceiver;
import com.waidi.clothespad.common.MyToast;
import com.waidi.clothespad.common.RfidData;
import com.waidi.clothespad.websocket.MyWebsocketClient;

import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.exceptions.WebsocketNotConnectedException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;



/**
 * Created by ll on 2017/12/15.
 */

public class handlethread extends Thread{
    public Handler handler0;//selef
    public Handler handler1;
    public Handler handler2=null;
    public Handler handler3=null;
    public Handler handler4;
    public boolean flag ;
    public DevData devData = null;
    public  int calltype = 0;
    public String deal_reslut = "";
    public String call_time = "";
    public String deal_time="";
    public boolean call_flag= false;
    public static int request_video = 0;
    public static int request_qc = 0;
    public static int commit_qc = 0;
    public Db myDbHelper = null;
    private static final String TAG = handlethread.class.getSimpleName();

    public Context context0;
    File image_dir;
    //注册广播
    public static final String NEW_LIFEFORM_DETECTED = "com.dxz.broadcasttest.NEW_LIFEFORM";
    protected MyBroadcastReceiver receiver;


    public MyWebsocketClient wsc = null;
    public boolean exceptionFlag = false;

    private int timeout = 0;
    private int getorderidtimeout = 0;
    public int timerworkerinfosynctimeout = 288;

    public int timerhangerinfosynctimeout = 9;

    private boolean conn = false;
    private boolean login = false;
    private String url = "ws://"+Config.devConfig.addr+":"+Config.devConfig.port;

    public handlethread(Handler handlerin,Context contextin)
    {
        handler0  = handlerin ;
        context0 = contextin;
        image_dir = new File(context0.getFilesDir().getAbsoluteFile().toString()+"/image");
        if (!image_dir.exists())
        {
            image_dir.mkdirs();//创建文件夹
            Log.i("handlethread: ", image_dir.toString());
        }
        Config config = new Config(context0);
        config.init();
    }

    public handlethread(  )
    {


    }


    void connect_server()
    {
        try
        {
            login =false;
            timeout = 0;
            url = "ws://"+Config.devConfig.addr+":"+Config.devConfig.port;
            wsc= new MyWebsocketClient( new URI( url),new Draft_6455()); // more about drafts here: http://github.com/TooTallNate/Java-WebSocket/wiki/Drafts
            wsc.context = context0;
            wsc.image_dir = image_dir;
            wsc.handler = handler0;
            wsc.handler1 = handler1;
            wsc.gxlxt_handler = handler2;//qczhijian
            wsc.myDbHelper = myDbHelper;
            wsc.devid = Config.devConfig.devid;
            wsc.setConnectionLostTimeout(300);
            exceptionFlag = false;
            wsc.heatout = 0;
            wsc.connect();
            Config.webscoekt_conn = false;
            Log.i("handlethread","webSocketService connect.......!" );
        }
        catch (URISyntaxException io)
        {
            io.printStackTrace();
           //MyToast.showToast();
        }

    }

    public void run()
    {

        int  first = 0;
        int heattimeoutflag = 0;
        while(true)
        {
            try {
                if(first==0) //connetc again
                {
                    first = 1;
                    connect_server();
                    Thread.sleep(3000);
                }else if(wsc==null)
                {
                    Thread.sleep(2000);
                    connect_server();
                }
                else if(wsc.isClosed())
                {
                    Thread.sleep(4000);
                    connect_server();
                }
                else if(heattimeoutflag==1)
                {
                    connect_server();
                    heattimeoutflag = 0;
                    Thread.sleep(3000);
                }
                else if(wsc.isOpen())
                {
                    try
                    {
                        Config.webscoekt_conn = true;
                        heattimeoutflag = 0;
                        //in opne fun has cureed
                        timeout++;
                        if(timeout==15)//3s
                        {
                            String ping = String.format("{\"action\":\"heart.info\",\"data\":{\"devid\":\"%s\",\"location\":\"%s\",\"heart\":\"ping\"}}", Config.qrcode,Config.qrCodeInfo.location);
                            wsc.send(ping);
                            timeout = 0;
                            wsc.heatout ++;
                            Log.i(TAG,ping);
                        }
                        //getorderidtimeout++;
                        if(getorderidtimeout==300)//无读卡器下 300采用定时器模式发送请求
                        {
                            getorderidtimeout = 0;
                            RfidData  tmp = new RfidData();
                            tmp.type = "02";
                            tmp.id = "";
                            tmp.data="";
                            Config.hgrfiddataqueue.offer(tmp);
                        }
                        timerworkerinfosynctimeout++;
                        if(timerworkerinfosynctimeout==300||Config.Workerinfosyncflag==1)
                        {
                            timerworkerinfosynctimeout = 0;
                            Config.Workerinfosyncflag = 0;
                            workinfosync();
                        }


                        if(Config.hangerinfosyncflag==1)
                        {
                            timerhangerinfosynctimeout++;
                            if(timerhangerinfosynctimeout==10)
                            {
                                timerhangerinfosynctimeout = 0;
                                hangeridsync();
                            }
                        }


                        if (wsc.heatout ==4) //
                        {
                            wsc.close();
                            Config.webscoekt_conn = false;
                            Log.i(TAG,"websocket heartout disconnet !");
                            wsc.conn = false;
                            wsc.heatout = 0;
                            login =false;
                            Bundle bundle2=new Bundle();
                            bundle2.putString("websocket","net_disconnect");
                            Message msg1;
                            msg1=handler1.obtainMessage();//每发送一次都要重新获取
                            msg1.setData(bundle2);
                            msg1.arg1 = 1;
                            handler1.sendMessage(msg1);//用handler向主线程发送信息
                            heattimeoutflag = 1;
                            Thread.sleep(200);
                            continue;
                        }

                        if(Config.dg_server_add_changed==true)
                        {
                            wsc.close();
                            Log.i(TAG,"websocket du dg server add changed and connect again!");
                            wsc.conn = false;
                            Config.webscoekt_conn = false;
                            wsc.heatout = 0;
                            login =false;
                            Config.dg_server_add_changed = false;
                            Thread.sleep(200);
                            continue;
                        }

                        if(Config.hgrfiddataqueue.size()!=0)
                        {
                            int i = 0;
                            JSONObject request = new JSONObject();
                            request.put("action", "real.info");
                            JSONObject data1 = new JSONObject();


                            String id0 = "33323438303834";
                            String id1 = "32313830323834";
                            String id2 = "39383430313834";
                            String id = "";
                            Config.readWriteLock.readLock().lock();
                            id = Config.hgrfiddataqueue.poll().id;
                            Log.i(TAG,id);
                            Config.current_hangerid = id ;
                            Config.readWriteLock.readLock().unlock();

/*                          int[]tmp = new int[4];
                            tmp[0]= (Integer.parseInt(id.substring(0))<<24 &0xFF000000);
                            tmp[1]= (Integer.parseInt(id.substring(1))<<16 &0x00FF0000);
                            tmp[2]= (Integer.parseInt(id.substring(2))<<8 &0x0000FF00);
                            tmp[3]= (Integer.parseInt(id.substring(3)) &0x000000FF);
                            long sum = tmp[0]+tmp[1]+tmp[2]+tmp[3];

                            String id33 = "";
                            String tt=Long.toString(sum);

                            int size = tt.length();
                            for(int s = size;s>0;s--)
                            {
                                id33 = id33+"3"+tt.substring(s-1);
                            }*/

                            data1.put("devid", Config.qrcode);
                            data1.put("hangerid", id);
                            String locaton=Config.qrCodeInfo.location;
                            data1.put("location", locaton);

/*                          if(a==0)
                            {
                                data1.put("hangerid", id0);
                                a=1;
                            }
                            else if(a==1)
                            {
                                data1.put("hangerid", id1);
                                a =2;
                            }
                            else if(a==2)
                            {
                                data1.put("hangerid", id2);
                                a = 0;
                            }*/

                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String t=format.format(new Date());
                            data1.put("realtime",t);
                            request.put("data",data1);

                            wsc.send(request.toString());
                            Log.i("handlethread:",request.toString());
                        }

                        if(Config.RePairFlag==1)
                        {
                            qc_repair();
                            Config.RePairFlag= 0;
                        }
                        if(request_video==1)
                        {

                        }
                        if(request_qc==1)
                        {
                        }
                        if(commit_qc==1)
                        {
                        }
                    }
                    catch (JSONException e)
                    {
                        e.printStackTrace();
                    }
                }
                else
                {
                    Config.dg_server_add_changed = false;
                    Config.webscoekt_conn = false;
                }
                Thread.sleep(200);
            }
            catch (InterruptedException e)
            {
                System.out.println("Thread "  + " interrupted.");
                e.printStackTrace();
            }

            catch (WebsocketNotConnectedException e)
            {
                if(wsc!=null)
                {
                    wsc.close();
                    wsc.conn = false;
                    exceptionFlag = true;
                    Config.webscoekt_conn = false;
                }
                e.printStackTrace();
            }
            catch (Exception t)
            {
                t.printStackTrace();
            }

        }
    }

    public void call_event()
    {
        try
        {
            JSONObject call = new JSONObject();
            call.put("action", "call.info");
            JSONObject data = new JSONObject();
            data.put("devid", Config.devConfig.devid);
            if(calltype==1)
            data.put("call_type","leader");
            if(calltype==2)
                data.put("call_type","repairer");
            if(calltype==3)
                data.put("call_type","bom");
            if(call_time.length()==0) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
                call_time = format.format(new Date());
                data.put("call_time", call_time);
            }else
                data.put("call_time", call_time);

            if(deal_reslut.length()==0)
            {
                data.put("deal_time","");
                data.put("deal_result",deal_reslut);
            }
            else
            {
                SimpleDateFormat formatt = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
                deal_time=formatt.format(new Date());
                data.put("deal_time", deal_time);
                data.put("deal_result",deal_reslut);
                call_time = "";
                deal_time="";
                deal_reslut="";

            }
            data.put("deal_workerid","");
            data.put("deal_name","");
            call.put("data",data);
            wsc.send(call.toString());
            Log.i("handlethread:",call.toString());

        }catch (JSONException e)
        {
            Log.i("handlethread",e.toString());
        }
    }


    public void request_video()
    {
        try {
            JSONObject requestvideo = new JSONObject();
            requestvideo.put("action", "video.info");
            JSONObject data = new JSONObject();
            devData.loadAppConfig();
            data.put("devid", Config.devConfig.devid);
            requestvideo.put("data",data);
            wsc.send(requestvideo.toString());
            Log.i("handlethread:",requestvideo.toString());

        }catch (JSONException e)
        {
            Log.i("handlethread",e.toString());
            e.printStackTrace();
        }
    }

    public void request_qcinfo()
    {
        try
        {

            JSONObject requestqc = new JSONObject();
            requestqc.put("action", "qc.request");
            JSONObject data = new JSONObject();
            devData.loadAppConfig();
            data.put("devid", Config.devConfig.devid);
            requestqc.put("data",data);
            wsc.send(requestqc.toString());
            Log.i("handlethread:",requestqc.toString());

        }catch (JSONException e)
        {
            Log.i("handlethread",e.toString());
            e.printStackTrace();
        }
    }

    public void qc_repair()
    {
        try {
            JSONObject requestqc = new JSONObject();
            requestqc.put("action", "order.return");
            JSONObject data = new JSONObject();

            data.put("devid", Config.qrcode);
            String locaton=Config.qrCodeInfo.location;
            data.put("location", locaton);


            data.put("failInfo", Config.RePairCodeString);
            data.put("cardno", Config.globalrealhangerid);

            requestqc.put("data",data);
            wsc.send(requestqc.toString());
            Log.i("handlethread:",requestqc.toString());

        }catch (JSONException e)
        {
            Log.i("handlethread",e.toString());
            e.printStackTrace();
        }
    }

    public void hangeridsync()  //返修的时候 刷新衣架ID
    {
        try {
            if(Config.rfidWorkerInfo.workernum.length()==0)
                return;
            JSONObject workinfosync = new JSONObject();
            workinfosync.put("action", "timer.order.return.cardNo");
            JSONObject data = new JSONObject();
            data.put("devid", Config.qrcode);
            String locaton=Config.qrCodeInfo.location;
            data.put("location", locaton);
            workinfosync.put("data",data);
            wsc.send(workinfosync.toString());
            Log.i("handlethread:",workinfosync.toString());
        }catch (JSONException e)
        {
            Log.i("handlethread",e.toString());
            e.printStackTrace();
        }
    }


    public void workinfosync()
    {
        try {
            //注销同步
            //if(Config.rfidWorkerInfo.workernum.length()==0)
            //    return;

            JSONObject workinfosync = new JSONObject();
            workinfosync.put("action", "timer.workerinfo.sync");
            JSONObject data = new JSONObject();

            data.put("devid", Config.qrcode);
            String locaton=Config.qrCodeInfo.location;
            data.put("location", locaton);
            data.put("empcode", Config.rfidWorkerInfo.workernum);

            String islogin = "1";
            if(Config.rfidWorkerInfo.workernum.length()==0)
            {
                islogin = "0";
            }


            data.put("islogin", islogin);

            workinfosync.put("data",data);
            wsc.send(workinfosync.toString());
            Log.i("handlethread:",workinfosync.toString());


        }catch (JSONException e)
        {
            Log.i("handlethread",e.toString());
            e.printStackTrace();
        }
    }

    public void commit_qc()
    {

        try {
            JSONObject commit_qc = new JSONObject();
            commit_qc.put("action", "qc.info");
            JSONObject data = new JSONObject();
            devData.loadAppConfig();
            data.put("devid", Config.devConfig.devid);
            data.put("order_id",Config.realinfo.order_id);
            data.put("style_id",Config.realinfo.style_id);
            data.put("style_cs",Config.realinfo.style_size+"/"+Config.realinfo.style_colour);
            data.put("style_id",Config.realinfo.style_id);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
            data.put("submit_time",format.format(new Date()));


            JSONArray qcArray = new JSONArray();
            Config A = new Config(context0);
            Config.QcCommit  info=  A.new QcCommit(null,null);

            for (int i=0; i<Config.qcCommitArrayList.size(); i++)
            {
                JSONObject tmp = new JSONObject();
              //  info = Config.qcCommitArrayList[i];
                //tmp.put("defect_desc",);



            }

            //qcArray.put("defect_detail",);
            commit_qc.put("defect_detail",data);
            wsc.send(commit_qc.toString());
            Log.i("handlethread:",commit_qc.toString());

        }catch (JSONException e)
        {
            Log.i("handlethread",e.toString());
            e.printStackTrace();
        }

    }

};
